package 剑指offer;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;

public class 剑指Offer32从上到下打印二叉树 {
    public int[] levelOrder(TreeNode root) {
        //创建一个临时的队列，用来保存当前节点，按照先序根左右的顺序开始遍历
        int[] arr = new int[0];
        if(root == null){
            return arr;
        }
        return help(root);
    }

    private int[] help(TreeNode root){
        Deque<TreeNode> queue = new ArrayDeque();
        ArrayList<Integer> list = new ArrayList<>();

        //先将root入队列
        queue.offer(root);

        //然后出队列
        while(!queue.isEmpty()){
            TreeNode node = queue.poll();
            list.add(node.val);
            if(node.left != null){
                queue.offer(node.left);
            }
            if(node.right != null){
                queue.offer(node.right);
            }
        }
        int size = list.size();
        int[] arr = new int[size];
        for(int i = 0;i < size;i++){
            arr[i] = list.get(i);
        }
        return arr;
    }
}
class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }
